import win32file
import threading
import win32con
import json
import time
import sys
import os



# 设置监听的文件操作类型
actions = {
    1: "创建",    
    2: "删除",
    3: "修改",
    4: "重命名"
}



_MainApp_ = sys.modules["_MainApp_"]
MFlask = sys.modules["mflask"]



def get_leidian_config(path):
    with open(path, "r", encoding='utf-8') as f:
        return json.loads(f.read())



def get_mnq_version(key):
    _version = {"3_32": "安卓5.1(32位)", "4_32": "安卓7.1(32位)", "4_64": "安卓7.1(64位)", "9_64": "安卓9.0(64位)"}
    return _version[key]



def mnq_model_add(MainPath, value):
    confile = os.path.basename(value).replace(".config", "")
    item = {"hwnd": 0, "id": confile.replace("leidian", ""), "isrunning": False, "name": ""}
    for i in range(10):
        leidianJson = get_leidian_config(os.path.join(MainPath["value"], "vms", value))
        if "statusSettings.playerName" in leidianJson:
            item["name"] = leidianJson["statusSettings.playerName"]
            break
        time.sleep(0.2)
    mnqId_path = os.path.join(MainPath["value"], "vms", "leidian{}".format(item["id"]))
    size_in_bytes = 0
    for vmdk in [os.path.join(mnqId_path, "data.vmdk"), os.path.join(mnqId_path, "sdcard.vmdk"), os.path.join(mnqId_path, "system.vmdk")]:
        if os.path.exists(vmdk):
            size_in_bytes += os.path.getsize(vmdk)
    item["size"] = "{} GB".format(round(size_in_bytes/(1024 * 1024 * 1024), 2))
    MFlask.CallClenT.Sendws({"type": "mnq_add", "value": item, "path": MainPath["value"]})
    _MainApp_.threadmain.emit("创建模拟器 {} [{}]".format(item["id"], get_mnq_version(MainPath["key"])), "message")



def mnq_model_del(MainPath, value):
    confile = os.path.basename(value).replace(".config", "")
    index = confile.replace("leidian", "")
    MFlask.CallClenT.Sendws({"type": "mnq_del", "status": False, "value": [index], "path": MainPath["value"]})
    _MainApp_.threadmain.emit("删除模拟器 {} [{}]".format(index, get_mnq_version(MainPath["key"])), "message")



def mnq_model_status(MainPath, value):
    confile = os.path.dirname(os.path.dirname(value))
    time.sleep(1)
    item = {"type": "", "status": False, "value": confile.replace("leidian", ""), "path": MainPath["value"]}
    status = "未知"
    try:
        osopen = os.open(os.path.join(MainPath["value"], "vms", confile, "system.vmdk"), os.O_RDWR | os.O_CREAT)
        os.close(osopen)
        item["type"] = "mnq_stop"
        status = "关闭"
    except PermissionError:
        item["type"] = "mnq_start"
        status = "启动"
    MFlask.CallClenT.Sendws(item)
    _MainApp_.threadmain.emit(status + "模拟器 {} [{}]".format(item["value"], get_mnq_version(MainPath["key"])), "message")



class Main(threading.Thread):
    def __init__(self, model):
        super(Main, self).__init__()
        self.daemon = True
        self.model = model
        self.hDir = win32file.CreateFile(
            os.path.join(self.model["value"], "vms"),
            win32con.GENERIC_READ,
            win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
            None,
            win32con.OPEN_EXISTING,
            win32con.FILE_FLAG_BACKUP_SEMANTICS,
            None
        )

    def run(self):
        while not _MainApp_.threadmain.stop_event.is_set():
            results = win32file.ReadDirectoryChangesW(
                self.hDir,
                1024,
                True,
                win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
                win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
                win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
                win32con.FILE_NOTIFY_CHANGE_SIZE |
                win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
                win32con.FILE_NOTIFY_CHANGE_SECURITY,
                None,
                None
            )
            for action, file in results:
                if file.startswith("leidian"):
                    if action == 3 or action == 1:
                        if file.endswith("VBox.log"):
                            threading.Thread(target=mnq_model_status, args=(self.model, file)).start()

                elif file.startswith("config"):
                    if file.endswith(".config"):
                        if action == 1:
                            threading.Thread(target=mnq_model_add, args=(self.model, file)).start()
                        elif action == 2:
                            threading.Thread(target=mnq_model_del, args=(self.model, file)).start()




def main():
	# 获取配置
    mconfig = sys.modules["mconfig"]
    for key in mconfig.LD_MODEL:
        if mconfig.LD_MODEL[key]:
            Main({"key": key, "value": mconfig.LD_MODEL[key]}).start()